package com.osdp.common.advice;

import com.osdp.common.http.Result;
import com.osdp.common.util.MessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
/**
 * 统一处理返回值的切面类
 * 这个切面会作用所有controller里面的方法
 */
@Slf4j
@ControllerAdvice
public class RestResultAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    /**
     * 将Restful接口的返回的数据，转换成统一的格式返回
     * @param o
     * @param methodParameter
     * @param mediaType
     * @param aClass
     * @param serverHttpRequest
     * @param serverHttpResponse
     * @return
     */
    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType,
                                  Class<? extends HttpMessageConverter<?>> aClass,
                                  ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {
        String webClientType = serverHttpRequest.getHeaders().getFirst("web-client-type");
//        log.debug("web-client-type: " + webClientType);
        if ("web".equals(webClientType)) {
            Object rep;
            if (o == null) {
                rep = Result.success(MessageUtil.getMessage(10049));
            } else if (o instanceof Result) {
                rep = o;
            } else if (o instanceof String) {
                rep  = Result.success(String.valueOf(o));
            } else if (o instanceof Boolean) {
                rep = Boolean.valueOf(o.toString()) ? Result.success(MessageUtil.getMessage(10049)) : Result.fail(MessageUtil.getMessage(10051));
            } else if (o instanceof ByteArrayResource){ // o.getClass().toString()获取对象类型 用于验证码
                rep = o;
            } else { //IPage
                rep = Result.success(o);
            }
            return rep;
        } else {
            return o;
        }
    }
}
